package com.xayq.orap.rest;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xayq.orap.model.Resource;
import com.xayq.orap.mvc.BaseController;
import com.xayq.orap.service.ResourceService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/resource")
public class ResourceController extends BaseController {
	
	@Autowired
	private ResourceService resourceService;
	
	@RequestMapping("/list")
	public void getResourceList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		OutputStream os = response.getOutputStream();
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		Gson gson = new GsonBuilder().disableHtmlEscaping().create();
		Map result = new HashMap();
		Map<String, String> reqMap = getParameterMap(request);
		Map params = new HashMap();
		int current = reqMap.get("current") == null ? 1 : Integer.parseInt(reqMap.get("current"));
		int rowCount = reqMap.get("rowCount") == null ? 10 : Integer.parseInt(reqMap.get("rowCount"));
		params.put("start", (current-1)*rowCount);
		params.put("limit", rowCount);
		for (Entry<String, String> entry : reqMap.entrySet()) {  
			if(entry.getKey().startsWith("sort[")){
				String sort = entry.getKey().split("\\[|\\]")[1]+" "+entry.getValue();
				params.put("sort", sort);
			}
		}
		List<Resource> rsList = resourceService.getResourceList(params);
		
		int totalCount = 0;
		if(rsList.size()>0){
			totalCount = resourceService.getTotalCount();
		}else{
			current = 0;
			rowCount = 0;
		}
		result.put("current", current+"");
		result.put("rowCount", rsList.size()+"");
		result.put("rows", rsList);
		result.put("total", totalCount+"");
		String jsonStr = gson.toJson(result);
		os.write(jsonStr.getBytes("utf-8"));
		
	};
	
	@RequestMapping("/exist")
	public void isResourceExist(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, String> reqMap = getParameterMap(request);
		String name = reqMap.get("name") == null ? "" :reqMap.get("name");
		String startValue = reqMap.get("startValue") == null ? "" : reqMap.get("startValue");
		if(name.equals(startValue)){
			response.getWriter().print(true);
		}else{
			if(resourceService.isResourceExist(name)){
			      response.getWriter().print(false);                                
			}
			else{
			      response.getWriter().print(true);
			}
		}		
	}
	
	@RequestMapping("/edit")
	public @ResponseBody Map resourceEdit(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map result = new HashMap();
		Map<String, String> reqMap = getParameterMap(request);
		String id = reqMap.get("id") == null ? "" :reqMap.get("id");
		String name = reqMap.get("name") == null ? "" :reqMap.get("name");
		String description = reqMap.get("description") == null ? "" :reqMap.get("description");
		Map params = new HashMap();
		params.put("name", name);		
		params.put("description", description);
		
		if(id.isEmpty()){
			try{
				resourceService.insertResource(params);
				result.put("success", true);
				result.put("msg", "资源新建成功");
			}catch(Exception e){
				result.put("success", false);
	    		result.put("msg", "资源新建失败，请重试");
			}
		}else{
			params.put("id", id);
			try{
				resourceService.updateResource(params);
				result.put("success", true);
				result.put("msg", "资源更新成功");
			}catch(Exception e){
				result.put("success", false);
	    		result.put("msg", "资源更新失败，请重试");
			}
		}
		return result;
		
	}
	
	@RequestMapping("/delete")
	public @ResponseBody Map resourceDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map result = new HashMap();
		Map<String, String> reqMap = getParameterMap(request);
		String rowIds = reqMap.get("rowIds") == null ? "" :reqMap.get("rowIds");
		try{
			resourceService.deleteResource(rowIds.split(","));
			result.put("success", true);
			result.put("msg", "资源删除成功");
		}catch(Exception e){
			result.put("success", false);
    		result.put("msg", "资源删除失败，请重试");
		}
		return result;
	}
	
}
